package com.feicheng.iou.advice;

import com.feicheng.iou.exception.SystemException;
import com.feicheng.iou.exception.SystemExceptionV110;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.result.ResultInfoV110;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author tianchunlei
 * @Des //v1.0.0版本统一异常处理类
 * @Date 2021/8/5
 **/
@ControllerAdvice
public class ControllerAdviceHandlerV110 {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerAdviceHandlerV110.class);
    private static final DateTimeFormatter LOCAL_DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter LOCAL_DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @ResponseBody
    @ExceptionHandler(SystemExceptionV110.class)
    public ResultInfoV110 handlerSystemException(SystemExceptionV110 e) {
        LOG.warn(e.getMessage());
        return ResultInfoV110.failOrError(
                e.getInformationBean().getCode(),
                e.getInformationBean().getMessage()
        );
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultInfoV110 handlerException(Exception e) {
        LOG.error("系统发生异常", e);
        return ResultInfoV110.failOrError("E001","系统发生异常");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                this.setValue(LocalDate.parse(text, LOCAL_DATE));
            }
        });
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                this.setValue(LocalDateTime.parse(text, LOCAL_DATE_TIME));
            }
        });
    }
}
